"""
路由拦截器扩展初始化
通过 @app.before_request 实现对全局路由的拦截
"""
import os
import json
import logging
import datetime
from typing import Dict, List, Optional
from flask import Flask, request, current_app,render_template,redirect
from apps.common.utils.route_manager import get_route_manager
from apps.modules.admin.models.sys.sys_plugin import SysPlugin

logger = logging.getLogger(__name__)


class RouteInterceptor:
    """路由拦截器扩展"""

    def __init__(self, app: Flask = None):
        """
        初始化路由拦截器扩展

        Args:
            app: Flask 应用实例
        """
        self.app = app
        self.route_manager = None
        # 拦截器配置
        self.interceptor_config = {
            'enabled': True,  # 是否启用拦截器
            'default_redirect_url': '/',  # 默认重定向URL
            'default_template': 'errors/408.html',  # 默认错误模板
        }
        if app is not None:
            self.init_app(app)

    def init_app(self, app: Flask):
        """
        初始化应用

        Args:
            app: Flask 应用实例
        """
        self.app = app


        # 初始化路由管理器和拦截器
        self.route_manager = get_route_manager(app)

        # 注册到应用
        self._register_to_app()

        # 设置插件启用状态
        with app.app_context():
            plugins = SysPlugin.query.order_by(SysPlugin.sort_order.asc()).all()
            for plugin in plugins:
                if plugin.status == 1:
                    self.route_manager.enable_plugin(plugin.name)
                else:
                    self.route_manager.disable_plugin(plugin.name)

        logger.info("路由拦截器扩展初始化完成")

    def _register_to_app(self):
        """注册到应用"""
        # 将路由管理器和拦截器添加到应用上下文
        self.app.route_manager = self.route_manager
        # 注册全局请求处理器
        self._register_global_handlers()
        logger.info("路由拦截器扩展已注册到应用")

    def _register_global_handlers(self):
        """注册全局请求处理器"""

        @self.app.before_request
        def global_route_interceptor():
            """全局路由拦截器"""
            # if not self.config['enabled']:
            #     return None

            # 获取当前请求路径
            request_path = request.path
            request_method = request.method

            # 检查是否需要拦截
            if self._should_intercept_request(request_path):
                # 判断插件是否启用
                if not self.route_manager.is_plugin_enabled(self.route_manager.get_route_plugin(request_path)):
                    logger.warning(f"路由拦截器阻止访问: {request_method} {request_path}")
                    return self._handle_unauthorized_access(request_path)
                pass

            return None

    def _should_intercept_request(self, request_path: str) -> bool:
        """
        判断是否应该拦截该请求

        Args:
            request_path: 请求路径

        Returns:
            bool: 是否应该拦截
        """
        # 根据URL判断插件是否启用
        if self.route_manager.is_plugin_route(request_path):
            return True
        return False
    def _handle_unauthorized_access(self, request_path: str):
        """
        处理未授权访问

        Args:
            request_path: 请求路径

        Returns:
            Response: 响应对象
        """
        # 记录访问日志
        logger.warning(f"未授权访问插件路由: {request_path} from {request.remote_addr}")

        # 根据配置返回不同的响应
        if self.interceptor_config['default_template']:
            try:
                return render_template(
                    self.interceptor_config['default_template'],
                    error_message="访问被拒绝",
                    request_path=request_path,
                    timestamp=datetime.datetime.now().isoformat()
                )
            except Exception as e:
                logger.error(f"渲染错误模板失败: {e}")
                return self._default_error_response()
        else:
            return redirect(self.interceptor_config['default_redirect_url'])

    def _default_error_response(self):
        """默认错误响应"""
        return f"""
        <html>
        <head><title>访问被拒绝</title></head>
        <body>
        <h1>访问被拒绝</h1>
        <p>您没有权限访问此页面。</p>
        <p><a href="{self.interceptor_config['default_redirect_url']}">返回首页</a></p>
        </body>
        </html>
        """, 403

# 创建扩展实例
route_interceptor = RouteInterceptor()


def init_route_interceptor(app: Flask):
    """
    初始化路由拦截器扩展
    Args:
        app: Flask 应用实例
    """
    return get_route_interceptor(app)

def get_route_interceptor(app: Flask = None) -> RouteInterceptor:
    """获取路由拦截器扩展实例"""
    global route_interceptor

    if app is None:
        from flask import current_app
        app = current_app

    if route_interceptor is None or route_interceptor.app != app:
        route_interceptor = RouteInterceptor(app)

    return route_interceptor